package com.zh.note.huawei.onehundred.五子棋迷;

import java.util.Arrays;

/**
 * @Author: zhanghuan
 * @date: 2023/8/15 12:36
 * @description: create it
 */
public class Main {
    public static void main(String[] args) {
        // Scanner sc = new Scanner(System.in);
        // int target = sc.nextInt();
        // String inputstr = sc.nextLine();
        // int target = 1;
        // String inputStr = "-1 0 1 1 1 0 1 0 1 -1 1";
        int target = -1;
        String inputStr = "-1 0 1 1 1 0 1 0 1 -1 1";
        String[] strs = inputStr.split(" ");
        int[] nums = Arrays.stream(strs).mapToInt(Integer::parseInt).toArray();
        int res = findMaxMatchIndex(nums, target);
        System.out.println(res);

    }

    private static int findMaxMatchIndex(int[] nums, int target) {
        int max = Integer.MIN_VALUE;
        int midDist = 0;
        int res = -1;
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            if (nums[i] == 0) {
                int left = i - 1;
                int right = i + 1;
                int leftCount = 0;
                int rightCount = 0;
                //计算左侧匹配次数
                while (left >= 0 && nums[left] == target && leftCount < 5) {
                    leftCount++;
                    left--;
                }
                if (leftCount > 4) {
                    continue;
                }
                // rightCount = leftCount;
                //计算右边匹配次数
                while (right < length && nums[right] == target && rightCount < 5) {
                    rightCount++;
                    right++;
                }
                //计算总匹配次数和中点的距离
                int totalCount = leftCount + rightCount;
                int distToMid = Math.abs(i - length / 2);

                if (totalCount > max || (totalCount == max && distToMid < midDist)) {
                    max = totalCount;
                    res = i;
                    midDist = distToMid;

                }
            }
        }
        return res;
    }

}
